package javaweb_work01.classesContrl.Servlet;

import javaweb_work01.classesContrl.Entity.Classes;
import javaweb_work01.classesContrl.Service.CheckClassesService;
import javaweb_work01.classesContrl.Service.StudentsSumService;
import javaweb_work01.main.Utils.PageContrl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

@WebServlet(name = "CheckClassesServlet", urlPatterns = "/checkClasses")
public class CheckClassesServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //解决POST接收乱码
        request.setCharacterEncoding("utf-8");
        //得到classes.jsp页面中传过来的输入框的内容
        String checkClassName = request.getParameter("checkClassName");
        //调用CheckClassesService的方法得到Classes对象的集合，即查找出来的班级信息
        CheckClassesService checkClassesService = new CheckClassesService();
        //传入得到的班级名称，返回一个Classes类对象的集合
        List<Classes> classes = checkClassesService.checkClassesService(checkClassName);

        //得到班级的人数
        StudentsSumService studentsSumService = new StudentsSumService();
        //声明一个Classes集合用于记录添加班级人数后的Classes对象
        for(Classes cs:classes){
            int i = studentsSumService.studentsSumService(cs.getCid());
            cs.setSum(i);
        }
        //将查找的班级集合中的班级数量作为需要显示的数据的总数，构造对象，用于控制分页
        PageContrl pageContrl = new PageContrl(0,5,classes.size());
        //将得到的PageContrl对象和Classes对象放入session中实现共享
        request.getSession().setAttribute("classesPageContrl",pageContrl);
        request.getSession().setAttribute("showClasses",classes);
        //跳转到班级管理页面
        response.sendRedirect("classes.jsp");
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request, response);
    }
}
